package org.jbrisk.text;

import java.util.Iterator;

import org.jbrisk.jinq.ISelector;

/**
 * Methods on string.
 * 
 * @author Rafael
 * 
 */
public class StringUtils {

	public static final String NEW_LINE = System.getProperty("line.separator");

	/**
	 * Indicates if a string is null or empty.
	 * 
	 * @param str
	 *            String to verify.
	 * @return True or false.
	 */
	public static boolean isNullOrEmpty(String str) {

		return str == null || str.length() == 0;
	}

	public static <T> String toDelimitedString(Iterable<T> items, String delimiter, ISelector<T, String> itemSelector) {

		String ret = "";

		if (items != null) {
			
			Iterator<T> iterator = items.iterator();

			if (iterator != null && iterator.hasNext()) {

				T item = iterator.next();

				if (itemSelector != null) {

					ret = itemSelector.select(item);

				} else {

					ret = item.toString();
				}

				if (iterator.hasNext()) {

					StringBuilder sb = new StringBuilder();

					sb.append(ret);

					do {

						sb.append(delimiter);

						item = iterator.next();
						
						if (itemSelector != null) {

							sb.append(itemSelector.select(item));

						} else {

							sb.append(item.toString());
						}
						
					} while (iterator.hasNext());
					
					ret = sb.toString();
				}
			}
		}

		return ret;
	}
}
